<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 16:22:13
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-13
-->
<template>
  <RjModal
    width="624px"
    drag
    :title="modalTitle"
    :visible="isVisible"
    :confirmLoading="confirmLoading"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form-model
      :labelCol="{ span: 10 }"
      :wrapperCol="{ span: 14 }"
      labelAlign="left"
      :model="accountForm"
      ref="accountFormRef"
      :rules="rules"
      :colon="false"
    >
      <a-form-model-item :label="$t('localAccount.name')" prop="username">
        <a-input
          allowClear
          :disabled="Boolean(accountForm.uuid)"
          v-model="accountForm.username"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('userManage.password')" prop="password">
        <a-input-password allowClear v-model="accountForm.password" />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('localAccount.authPolicy')"
        prop="profileId"
      >
        <a-select
          :loading="selectLoading"
          :filterOption="filterOption"
          showSearch
          v-model="accountForm.profileId"
          :options="groupOptions"
        >
          <div slot="dropdownRender" slot-scope="menu">
            <v-nodes :vnodes="menu" />
            <a
              style="padding: 4px 8px 8px; cursor: pointer; display: block"
              @mousedown="(e) => e.preventDefault()"
              @click="onAddAuthPolicy"
            >
              <icon-font type="ic-plus" />
              {{ $t('localAccount.addAuthPlicy2') }}
            </a>
          </div>
        </a-select>
        <div
          style="color: #999"
          v-show="!accountForm.profileId && accountForm.uuid"
        >
          {{ $t('userManage.oldAccountUnbindUserGroup') }}
        </div>
      </a-form-model-item>
      <div
        class="expand-item"
        @click="userInfoSetExpanded = !userInfoSetExpanded"
      >
        <span>{{ $t('userManage.userInfoSet') }}</span>
        <icon-font :type="userInfoSetExpanded ? 'ic-up' : 'ic-down'" />
      </div>
      <div v-if="userInfoSetExpanded">
        <a-form-model-item :label="$t('userManage.firstName')" prop="firstName">
          <a-input allowClear v-model="accountForm.firstName" />
        </a-form-model-item>

        <a-form-model-item :label="$t('userManage.lastName')" prop="lastName">
          <a-input allowClear v-model="accountForm.lastName" />
        </a-form-model-item>

        <a-form-model-item prop="email" :label="$t('userManage.email')">
          <a-input allowClear v-model="accountForm.email" />
        </a-form-model-item>

        <a-form-model-item :label="$t('userManage.phone')" prop="phone">
          <a-input allowClear v-model="accountForm.phone" />
        </a-form-model-item>

        <a-form-model-item :label="$t('userManage.alias')" prop="comment">
          <a-input allowClear v-model="accountForm.comment" />
        </a-form-model-item>
      </div>
    </a-form-model>
  </RjModal>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import { mapState } from 'vuex';
import { getByteLength } from '@/utils';
import { ValiDateTools } from '@/utils';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import lodash from 'lodash';
export default {
  name: 'addLocalAccountModal',
  mixins: [authSysMixin],
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    const checkUsername = (rule, val, cb) => {
      let length = getByteLength(val);
      if (
        length < 1 ||
        length > 32 ||
        !ValiDateTools.alphaNumericUnderscoreRegex.test(val)
      ) {
        cb(new Error(this.$t('userManage.accountUsernameTip')));
      } else {
        cb();
      }
    };
    const checkPassword = (rule, val, cb) => {
      let length = getByteLength(val);
      if (
        length < 2 ||
        length > 32 ||
        !/^[a-zA-Z0-9<=>\\[\]!@#$*().\x22]{2,32}$/.test(val)
      ) {
        cb(new Error(this.$t('userManage.accountPwdTip')));
      } else {
        cb();
      }
    };
    const checkEmail = (rule, val, cb) => {
      let length = getByteLength(val);
      if (val && length > 64) {
        cb(new Error(this.$t('userManage.commentLengthTip')));
      } else if (val && !ValiDateTools.emailRegex.test(val)) {
        cb(new Error(this.$t('userManage.enterCorrectEmail')));
      } else {
        cb();
      }
    };
    const checkName = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 60) {
          cb(new Error(this.$t('userManage.nameLengthTip')));
          // } else if (!ValiDateTools.alphaNumericUnderscoreRegex.test(val)) {
          //   cb(new Error(this.$t('userManage.enterNumbersLettersUnderscores')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };
    const checkPhone = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 25) {
          cb(new Error(this.$t('userManage.phoneLengthTip')));
        } else if (!ValiDateTools.numericRegex.test(val)) {
          cb(new Error(this.$t('userManage.phoneNumberTip')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };
    const checkComment = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 64) {
          cb(new Error(this.$t('userManage.commentLengthTip')));
        } else if (!ValiDateTools.alphaNumericUnderscoreBlankRegex.test(val)) {
          cb(new Error(this.$t('userManage.enterNumbersLettersUnderscores')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };
    const rules = {
      username: [
        {
          required: true,
          trigger: 'blur',
          message: this.$t('userManage.fieldIsRquired'),
        },
        {
          required: true,
          trigger: 'change',
          validator: checkUsername,
        },
      ],
      password: [
        {
          required: true,
          trigger: 'blur',
          message: this.$t('userManage.fieldIsRquired'),
        },
        {
          required: true,
          trigger: ['change', 'blur'],
          validator: checkPassword,
        },
      ],
      profileId: [
        {
          required: true,
          trigger: 'change',
          message: this.$t('userManage.fieldIsRquired'),
        },
      ],
      email: [
        {
          trigger: ['change', 'blur'],
          validator: checkEmail,
        },
      ],
      firstName: [
        {
          trigger: ['change', 'blur'],
          validator: checkName,
        },
      ],
      lastName: [
        {
          trigger: ['change', 'blur'],
          validator: checkName,
        },
      ],
      phone: [
        {
          trigger: ['change', 'blur'],
          validator: checkPhone,
        },
      ],
      comment: [
        {
          trigger: ['change', 'blur'],
          validator: checkComment,
        },
      ],
    };
    return {
      isVisible: false,
      accountForm: {
        username: '',
        password: '',
        profileId: '',
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        comment: '',
      },
      userInfoSetExpanded: false,
      rules,
      confirmLoading: false,
      selectLoading: false,
    };
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),
    modalTitle() {
      return this.accountForm.uuid
        ? this.$t('userManage.accountModalEditAccount')
        : this.$t('userManage.accountModalAddAccount');
    },
    groupOptions() {
      return this.authPolicys.map(
        (item) =>
          (item = {
            ...item,
            ...{ label: item.name, value: item.uuid },
          })
      );
    },
  },
  methods: {
    setAuthPolicyId(policyId) {
      this.accountForm.profileId = policyId;
    },
    onAddAuthPolicy() {
      this.$emit('addAuthPolicy');
    },
    openModal(record) {
      this.isVisible = true;
      if (record) {
        this.accountForm = lodash.cloneDeep(record);
      }
    },
    onOk() {
      this.$refs.accountFormRef.validate((valid) => {
        if (!valid) {
          return false;
        }
        if (this.accountForm.uuid) {
          this.saveAccount({ operation: 'edit' });
        } else {
          this.saveAccount();
        }
      });
    },
    async saveAccount(paramObj = { operation: 'add' }) {
      let querys = null;
      let replaces = null;
      let successTxt = '';
      let url = '';

      if (paramObj.operation === 'add') {
        querys = {
          tenantId: this.tenantInfo.tenantId,
          group_id: this.groupId,
        };
        replaces = {
          tenantName: encodeURI(this.tenantInfo.tenantName),
          userName: encodeURI(this.userInfo.account).trim(),
          groupId: this.groupId,
        };
        successTxt = this.$t('common.addSuceess');
        url = maccApi.MACC_ACCOUNT_ADD_POST_API;
      } else {
        querys = {
          tenantId: this.tenantInfo.tenantId,
        };
        replaces = {
          groupId: this.groupId,
        };
        successTxt = this.$t('common.editSuccess');
        url = maccApi.MACC_ACCOUNT_UPDATE_POST_API;
      }
      let params = { ...this.accountForm };
      params.userGroupId = params.profileId;
      this.confirmLoading = true;

      let res = await this.requestHttpAuth({
        api: url,
        method: 'POST',
        querys,
        params,
        replaces,
      });

      this.confirmLoading = false;
      if (res.data.code === 0) {
        this.$message.success(successTxt);
        this.$emit('refreshList');
        this.onCancel();
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    onCancel() {
      this.resetForm();
      this.isVisible = false;
    },
    resetForm() {
      this.accountForm = {
        username: '',
        password: '',
        profileId: '',
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        comment: '',
      };
    },
    /**
     * @description: 过滤用户组
     * @param {*} input
     * @param {*} option
     * @return {*}
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-form-item {
  margin-bottom: 8px;
}
.expand-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #000000e5;
  cursor: pointer;
  margin-bottom: 16px;
  font-weight: 500;
  i {
    margin-top: 3px;
    font-size: 18px;
  }
}
</style>
